package com.aida.evil.eda.fragment;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;

import com.aida.evil.aida.R;
import com.aida.evil.eda.Adapter.CommonAdapter;
import com.aida.evil.eda.Adapter.ViewHolder;
import com.aida.evil.eda.Data.NetworkData;
import com.aida.evil.eda.Data.UserData;
import com.aida.evil.eda.Login.SetUser;
import com.aida.evil.eda.MyView.ListViewForScrollView;
import com.aida.evil.eda.Toast.CustomSuperActivityToast;
import com.aida.evil.eda.Volley.VolleyHandler;
import com.aida.evil.eda.Volley.VolleyHttpRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.squareup.picasso.Picasso;
import com.yalantis.phoenix.PullToRefreshView;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/****************************************************
 * com.aida.evil.eda.fragment.My
 * 作者：白雨濃  evil
 * 时间：16-2-17 12:09
 * 邮箱：evilbai@foxmail.com
 * 页面用途：主界面 我的 界面fragment
 ****************************************************/
public class My extends Fragment
{
    /*加载item文字内容*/
    private final static String URL = "http://" + NetworkData.ServiceIP + "/GetOverItem?"
            + "userPhoneNum=" + UserData.DATA_PHONENUM;

    /*加载item图片内容*/
    private static final String IMGURL =
            "http://" + NetworkData.ServiceIP + "/ItemImg?ItemImg=";

    private ScrollView scrollView;
    private ListViewForScrollView listView;
    private My_Item_Adapter adapter;


    private View view;
    private ProgressBar progressBar;
    private PullToRefreshView pullToRefreshView;
    private ImageView userPortraitimg;/*用户头像*/
    private TextView userPHONENUM, userName, userIntegral;/*用户电话号，用户名，用户积分*/

    private ArrayList<My_ItemBeans> my_items = new ArrayList<>();


    /**
     * 再重新显示这个fragment时滑动
     * <p/>
     * !!!!!!!!!!!!!!!!有问题,重新加载的时候不能滑动到顶端
     */

    @Override
    public void onStart()
    {
        super.onStart();
        scrollView.smoothScrollTo(0, 0);//使得scrollView滑动到最顶端
    }


    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState)
    {
        view = inflater.inflate(R.layout.mainactivity_fragment_my, container, false);
        findviewById();/*查找控件*/
        toNetwork();/*网络请求*/
        set_userData();/*设置顶部的用户区域*/
        listview();/*初始化listview*/

        scrollView.smoothScrollTo(0, 0);//使得scrollView滑动到最顶端
        onClick();//设置监听
        return view;
    }

    /**
     * 网络请求
     */
    private void toNetwork()
    {
        progressBar.setVisibility(View.VISIBLE);
        VolleyHandler<String> stringVolleyHandler = new VolleyHandler<String>()
        {
            ItemList itemList;

            @Override
            public void reqSuccess(String response)
            {
                Gson gson = new Gson();
                Type type = new TypeToken<ItemList>()
                {
                }.getType();
                //itemList = gson.fromJson(response, ItemList.class);
                itemList = gson.fromJson(response, type);
                ArrayList<Item> items = itemList.items;
                for (Item item : items)
                {
                    my_items.add(new My_ItemBeans(item.itemID, item.itemImg, item.itemTitle, item.itemContext));
                }
                progressBar.setVisibility(View.GONE);
                refreshHandler.sendEmptyMessage(0);
            }

            @Override
            public void reqError(String error)
            {
                refreshHandler.sendEmptyMessage(0);
            }
        };
        VolleyHttpRequest.String_request(URL, stringVolleyHandler);
    }

    /**
     * 初始化ListView
     */
    private void listview()
    {
        adapter = new My_Item_Adapter(getContext()
                , my_items, R.layout.mainactivity_fragment_eda_listview_item);
        listView.setAdapter(adapter);


        pullToRefreshView.setOnRefreshListener(new PullToRefreshView.OnRefreshListener()
        {
            @Override
            public void onRefresh()
            {
                pullToRefreshView.postDelayed(new Runnable()
                {
                    @Override
                    public void run()
                    {
                        pullToRefreshView.setRefreshing(true);
                        my_items.clear();
                        toNetwork();
                    }
                }, 1000);
            }
        });

    }

    /**
     * 刷新listview
     */
    Handler refreshHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            adapter.notifyDataSetChanged();
            //refreshView.finishRefreshing();
            pullToRefreshView.setRefreshing(false);
        }
    };

    /**
     * 查找控件
     */
    private void findviewById()
    {
        listView = (ListViewForScrollView) view.findViewById(R.id.mainactivity_fragment_my_listview);
        scrollView = (ScrollView) view.findViewById(R.id.mainactivity_fragment_my_scrollView);

        userPortraitimg = (ImageView) view.findViewById(R.id.userPortraitimg);
        userPHONENUM = (TextView) view.findViewById(R.id.userPHONENUM);
        userName = (TextView) view.findViewById(R.id.userName);
        userIntegral = (TextView) view.findViewById(R.id.userIntegral);

        progressBar = (ProgressBar) view.findViewById(R.id.mainactivity_fragment_my_progressBar);

        pullToRefreshView = (PullToRefreshView) view.findViewById(R.id.mainactivity_fragment_my_pullToRefreshView);
    }

    /**
     * 设置用户内容
     * 包括 ： 头像（以后实行），IMEI（不可以设置），用户名，积分（不可设置）
     */
    private void set_userData()
    {
        userPHONENUM.setText("手机号：" + UserData.DATA_PHONENUM);
        userName.setText("用户名：" + UserData.DATA_USERNAME);
        userIntegral.setText("积分：" + UserData.DATA_INTEGRAL);
    }

    /**
     * 设置监听
     */
    private void onClick()
    {
        /*设置头像图片监听*/
        userPortraitimg.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                CustomSuperActivityToast.makeText(getActivity(), "暂时还不能自定义头像哦!", "确定").show();
            }
        });

        /*设置顶部用户信息区监听*/
        view.findViewById(R.id.mainactivity_fragment_my_cardView)
                .setOnClickListener(new View.OnClickListener()
                {
                    @Override
                    public void onClick(View v)
                    {
                        Intent intent = new Intent(getActivity(), SetUser.class);
                        startActivity(intent);
                    }
                });
    }


    /*++++++++++++++++++++++++++++++++++私有内部类，用于listview++++++++++++++++++++++++++++++++++++++*/

    /**
     * 适配器
     */
    private class My_Item_Adapter extends CommonAdapter<My_ItemBeans>
    {

        public My_Item_Adapter(Context context, List<My_ItemBeans> itemBean_list, int itemLayoutResId)
        {
            super(context, itemBean_list, itemLayoutResId);
        }

        @Override
        public void convert(ViewHolder viewHolder, My_ItemBeans item)
        {
            ImageView imageView = viewHolder.getView(R.id.eda_listview_item_imageView);
            TextView title = viewHolder.getView(R.id.eda_listview_item_title);
            TextView context = viewHolder.getView(R.id.eda_listview_item_context);

            Picasso.with(this.context)
                    .load(IMGURL + item.itemImg)
                    .placeholder(R.mipmap.loading)
                    .into(imageView);

            title.setText(item.itemTitle);
            context.setText(item.itemContext);
        }
    }

    /**
     * item的内容
     */
    private class My_ItemBeans
    {
        private int imageView;
        private int itemId;
        private String itemImg;
        private String itemTitle;
        private String itemContext;

        public My_ItemBeans(int itemId, String itemImg, String itemTitle, String itemContext)
        {
            this.itemId = itemId;
            this.itemImg = itemImg;
            this.itemTitle = itemTitle;
            this.itemContext = itemContext;
        }
    }

    /**
     * 解析json使用的内部类
     */
    protected class ItemList
    {
        protected String userPhoneNum;/* 发送IMEI，判断JSON准确性 */
        protected int itemSize;/* 该JSON大小，方便使用 */
        protected ArrayList<Item> items = new ArrayList<>();
    }

    /**
     * 解析json使用的内部类
     */
    protected class Item
    {
        protected int itemID;
        protected String itemImg;
        protected String itemTitle;
        protected String itemContext;
    }


}











